package com.example.api.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.api.annotation.AuthCheck;
import com.example.api.common.*;
import com.example.api.constant.UserConstant;
import com.example.api.exception.BusinessException;
import com.example.api.exception.ThrowUtils;
import com.example.api.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.example.api.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.example.api.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.example.api.model.entity.InterfaceInfo;
import com.example.api.model.entity.User;
import com.example.api.model.vo.InterfaceInfoVo;
import com.example.api.service.InterfaceInfoService;
import com.example.api.service.UserService;
import org.example.jingclientsdk.client.JingApiClient;
import org.example.jingclientsdk.model.HealthInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("interface")
public class InterfaceController {

    @Autowired
    private InterfaceInfoService interfaceInfoService;

    @Autowired
    private UserService userService;

    @Resource
    private JingApiClient jingApiClient;


    /**
     * 根据 id 获取实体（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<InterfaceInfo> getById(@RequestParam long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo entity = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(entity == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(entity);
    }


    /**
     * 根据 id 获取视图（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<InterfaceInfoVo> getVoById(@RequestParam Long id, HttpServletRequest request) {
        BaseResponse<InterfaceInfo> response = getById(id, request);
        InterfaceInfo entity = response.getData();
        return ResultUtils.success(interfaceInfoService.getVo(entity));
    }


    /**
     * 分页获取实体列表（仅管理员）
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfo>> listByPage(@RequestBody InterfaceInfoQueryRequest queryRequest,
                                                        HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        Page<InterfaceInfo> page = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(queryRequest));
        return ResultUtils.success(page);
    }

    /**
     * 分页获取视图列表
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<InterfaceInfoVo>> listVOByPage(@RequestBody InterfaceInfoQueryRequest queryRequest,
                                                            HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> page = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(queryRequest));
        Page<InterfaceInfoVo> VOPage = new Page<>(current, size, page.getTotal());
        List<InterfaceInfoVo> VOList = interfaceInfoService.getVOList(page.getRecords());
        VOPage.setRecords(VOList);
        return ResultUtils.success(VOPage);
    }


    /**
     * 创建
     *
     * @param addRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> add(@RequestBody InterfaceInfoAddRequest addRequest, HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo entity = new InterfaceInfo();
        BeanUtils.copyProperties(addRequest, entity);
        User loginUser = userService.getLoginUser(request);
        entity.setUserId(loginUser.getId());
        entity.setCreateTime(new Date());
        boolean result = interfaceInfoService.save(entity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(entity.getId());
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> delete(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = interfaceInfoService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param updateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> update(@RequestBody InterfaceInfoUpdateRequest updateRequest,
                                        HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo entity = new InterfaceInfo();
        BeanUtils.copyProperties(updateRequest, entity);
        boolean result = interfaceInfoService.updateById(entity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 发布
     *
     * @param idRequest
     * @param request
     * @return
     */
// 声明该方法为一个HTTP POST请求处理方法，处理路径是"/online"，用于发布接口
    @PostMapping("/online")
// 该接口仅管理员可用
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        // 如果id为null或者id小于等于0
        if (idRequest == null || idRequest.getId() <= 0) {
            // 抛出业务异常，表示请求参数错误
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1.校验该接口是否存在
        // 获取idRequest对象的id属性值
        long id = idRequest.getId();
        // 根据id查询接口信息数据
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        // 如果查询结果为空
        if (oldInterfaceInfo == null) {
            // 抛出业务异常，表示未找到数据
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 2.判断该接口是否可以调用
        HealthInfo health = jingApiClient.getHealth();
        ThrowUtils.throwIf(health == null, ErrorCode.SYSTEM_ERROR);

        //3.修改接口状态
        InterfaceInfo newInterfaceInfo = new InterfaceInfo();
        newInterfaceInfo.setId(id);
        newInterfaceInfo.setStatus(1);
        boolean result = interfaceInfoService.updateById(newInterfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 下线
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                      HttpServletRequest request) {
        // 如果id为null或者id小于等于0
        if (idRequest == null || idRequest.getId() <= 0) {
            // 抛出业务异常，表示请求参数错误
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1.校验该接口是否存在
        // 获取idRequest对象的id属性值
        long id = idRequest.getId();
        // 根据id查询接口信息数据
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        // 如果查询结果为空
        if (oldInterfaceInfo == null) {
            // 抛出业务异常，表示未找到数据
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //3.修改接口状态
        InterfaceInfo newInterfaceInfo = new InterfaceInfo();
        newInterfaceInfo.setId(id);
        newInterfaceInfo.setStatus(2);
        boolean result = interfaceInfoService.updateById(newInterfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


}
